<!-- 鱼塘估产（传统） -->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar :page-no="42" :add-active="addActive" :del-active="delActive" :edit-active="editActive"
        :cancel-active="cancelActive" :save-active="saveActive" :has-edit="false" :has-save="false" :has-cancel="false"
        @add="add" @cancel="cancel('formData')" @edit="edit" @del="del" @save="save('formData')" />
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">选择鱼塘</div>
            <el-select filterable clearable v-model="searchList.fishPondId" filterable clearable @change="() => {
              $set(searchList, 'productionBatchId', '')
            }">
              <el-option v-for="(item, index) in pondList" :key="index" :label="item.pondName" :value="item.fishPondId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">批次编号</div>
            <el-select filterable clearable v-model="searchList.productionBatchId" filterable clearable>
              <template v-for="(item, index) in batchList">
                <el-option v-if="!searchList.fishPondId || item.fishPondId == searchList.fishPondId" :key="index"
                  :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId" />
              </template>
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">估产人</div>
            <el-select filterable clearable v-model="searchList.staffId" filterable clearable>
              <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffId" />
            </el-select>
          </div>
          <div class="select-box-content select-box-leng-content">
            <div class="select-box-content-name">估产日期</div>
            <el-date-picker v-model="searchList.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table v-loading="false" :data="tableData" stripe border height="calc(100% - 50px)" @row-click="handleEdit"
        @selection-change="handleSelectionChange" ref="tableData">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="fishPondName" min-width="100" label="鱼塘名称">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.fishPondName ? scope.row.fishPondName : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="mnecode" min-width="100" label="估产批次">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.mnecode ? scope.row.mnecode : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="inputNum" min-width="100" label="投塘数（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.inputNum ? scope.row.inputNum : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="batchNum" min-width="100" label="在塘数（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.batchNum ? scope.row.batchNum : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="deadNum" min-width="100" label="直鱼数（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.deadNum ? scope.row.deadNum : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="produceNum" min-width="100" label="产出数（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.produceNum ? scope.row.produceNum : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="samplingQuantity" label="抽检数量（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.samplingQuantity ? scope.row.samplingQuantity : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="估产数量（尾）">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            {{ scope.row.batchNum ? scope.row.batchNum : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="avgWeight" label="估产均重（斤）"></el-table-column>
        <el-table-column prop="totalWeight" label="估产重量（斤）"></el-table-column>
        <el-table-column min-width="120" prop="density" label="标准养殖密度" />
        <el-table-column min-width="120" prop="estimateDensity" label="实际养殖密度" />
        <el-table-column prop="staffName" label="估产人"></el-table-column>
        <el-table-column min-width="200" prop="samplingDateTime" label="估产日期"></el-table-column>
        <el-table-column label="详情">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            <el-button type="text" class="text-btn-cursor" @click="edit('lookOver')">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.predictYieldId" slot-scope="scope">
            <el-button class="text-btn-cursor" v-if="scope.row.batchStatus !== 'UN_COMPLETE'" type="text" size="small"
              @click="$notify({
                title: '警告',
                message: '该批次完成无法编辑',
                type: 'warning'
              });">修改</el-button>
            <el-button class="text-btn-cursor" v-else type="text" size="small" @click="edit">修改</el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="(titleText || '') + '估产信息'" :visible.sync="dialogFormVisible" :before-close="cancel" width="40%">
        <el-form ref="formData" label-position="left" :model="formData" class="el-form" :rules="rules"
          :disabled="lookOver" :show-message="isshowrulemessage">
          <el-form-item label="鱼塘名称:" prop="fishPondId" class="w50p" v-if="nowChanceStau == 'add'">
            <el-select filterable clearable v-model="formData.fishPondId" clearable filterable placeholder="请选择鱼塘" @change="getBatchByPond">
              <el-option v-for=" item  in  fishPondArr " :key="item.fishPondId" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="titleText == '查看'" label="批次编号:" class="w50p">
            <el-input v-model="formData.mnecode"></el-input>
          </el-form-item>
          <el-form-item v-show="titleText !== '查看'" label="批次编号:" prop="batchList" class="w50p">
            <el-select filterable clearable v-model="formData.batchList" value-key="productionBatchId" clearable filterable
              placeholder="请先选择鱼塘" @change="getspecification">
              <el-option v-for=" item  in  selectBatchList " :key="item.productionBatchId"
                :label="`${item.mnecode}_${item.varietyName}`" :disabled="!item.num"
                :value="{
                  productionBatchId: item.productionBatchId,
                  fishVarietyId: item.fishVarietyId,
                  fishPondId: item.fishPondId,
                }
                  " />
            </el-select>
          </el-form-item>
          <el-form-item label="估产鱼种:" class="w50p">
            <el-input v-model="varietyName" type="string" placeholder="请先选择批次" clearable disabled />
          </el-form-item>
          <el-form-item label="估产组数:" class="w50p" v-if="nowChanceStau === 'add'">
            <el-input v-model="groupNum" type="number" placeholder="请先选择批次，再输入估产组数" clearable
              @change="samplingQuantityChange" :disabled="!formData.batchList" />
          </el-form-item>
          <el-form-item label="估产人:" prop="staffId" class="w50p">
            <el-select filterable clearable disabled v-model="formData.staffId" filterable clearable placeholder="请选择" @change="staffChange">
              <el-option v-for=" item  in  staffList " :key="item.staffId" :label="item.staffName"
                :value="item.staffId" />
            </el-select>
          </el-form-item>
          <el-form-item label="估产日期:" prop="samplingDateTime" class="w50p">
            <el-date-picker v-model="formData.samplingDateTime" type="datetime" value-format="yyyy-MM-dd hh:mm:ss"
              clearable :picker-options="pickerOptions" />
          </el-form-item>
          <el-divider></el-divider>
          <el-form-item v-for="( predictYieldData, index ) in  formData.predictYieldDetailList "
            :key="predictYieldData.key" class="w100p">
            <el-form-item label="规格:" :prop="'predictYieldDetailList.' + index + '.specificationId'" :rules="{
              required: true,
              message: '规格不能为空',
              trigger: 'change',
            }
              " class="w50p">
              <el-select filterable clearable v-model="predictYieldData.specificationId" placeholder="选择规格" filterable clearable>
                <el-option v-for="( item, index ) in  specificationList " :key="index" :label="item.specificationName"
                  :value="item.specificationId" />
              </el-select>
            </el-form-item>
            <el-form-item label="抽检尾数" :prop="'predictYieldDetailList.' + index + '.num'" :rules="[
              { required: true, message: '尾数不能为空', trigger: 'blur' },
              { validator: checkInteger, trigger: ['change', 'blur'] }
            ]
              " class="w50p">
              <el-input v-model="predictYieldData.num" placeholder="输入抽检尾数" clearable>
                <template slot="append">尾</template>
              </el-input>
            </el-form-item>
            <el-form-item label="估产总重" :prop="'predictYieldDetailList.' + index + '.weight'" :rules="[
              { required: true, message: '重量不能为空', trigger: 'blur' },
              { validator: checkInt, trigger: ['change', 'blur'] }
            ]
              " class="w50p">
              <el-input v-model="predictYieldData.weight" placeholder="输入单条重量" clearable>
                <template slot="append">斤</template>
              </el-input>
            </el-form-item>
            <div class="w100p addE" v-show="!lookOver">
              <div class="line-clicks" v-if="(nowChanceStau === 'edit')"
                @click="countList(predictYieldData, predictYieldData.predictYieldId, index)">{{
                  predictYieldData.predictYieldId ?
                  '修改' : '添加' }}</div>
              <div class="line-clicks"
                v-if="nowChanceStau === 'edit' && formData.predictYieldDetailList.length > 1 && predictYieldData.predictYieldId"
                @click="delProduceList(predictYieldData, index)">删除</div>
              <div class="line-click"
                v-if="(formData.predictYieldDetailList.length > 1 && nowChanceStau === 'add') || (formData.predictYieldDetailList.length > 1 && nowChanceStau === 'edit' && !predictYieldData.predictYieldId)"
                @click="delCountList(index)">
                <i class="el-icon-minus"></i>
              </div>
              <div
                v-if="nowChanceStau === 'add' && index === formData.predictYieldDetailList.length - 1 || nowChanceStau === 'edit' && index === formData.predictYieldDetailList.length - 1"
                class="line-click" @click="addCountList()">
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" v-if="nowChanceStau !== '' && !lookOver" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import InPondEstimationApi from "@/api/in-pond-estimation";
import InPondEstimationDetailApi from "@/api/in-pond-estimation/in-pond-estimation-detail";
import batchApi from "@/api/batch-mange/index";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import staffApi from "@/api/basic-info-manage/staff/index";
import specificationApi from "@/api/basic-info-manage/specification/index";
let maxTime = null
export default {
  name: "InPondEstimation",
  components: { ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      pondList: [],
      lookOver: false,
      dialogFormVisible: false,
      varietyName: '',
      samplingQuantityNum: 10,
      isshowrulemessage: false,
      // 下拉选择框相关
      productionBatchId: undefined,
      // 批次选择列表
      batchList: [],
      selectBatchList: [],
      // 估产规格
      specificationList: [],
      // 估产单位
      unitList: [],
      fishPondArr: [],
      titleText: '查看',
      //组数
      groupNum: '',
      // 搜索框对象
      searchList: {},
      rules: {
        batchList: [
          { required: true, message: "请选择批次", trigger: "blur" }
        ],
        staffId: [
          { required: true, message: "请选择估产人", trigger: "blur" }
        ],
        samplingDateTime: [
          { required: true, message: "请选择估产日期", trigger: "blur" }
        ]
      },
      name: "",
      staffList: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    isshowrulemessage: {
      handler (flag) {
        if (!flag) {
          this.groupNum = ''
          this.varietyName = ''
          this.$refs.formData && this.$refs.formData.clearValidate()
        }
      },
      deep: true
    },
    nowChanceStau (newvalue) {
      console.log('---------------', newvalue)
      maxTime = null
      if (newvalue === "add") {
        this.groupNum = ''
        this.varietyName = ''
        let staffName = sessionStorage.getItem('staffName')
        let staffId = Number(sessionStorage.getItem('staffId'))
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
          samplingDateTime: this.getNowTime(),
          fishPondId: ''
        }
        batchApi.queryByCondition({
          breedTypeNo: "TRADITIONAL_BREED",
        }).then(res => {
          this.batchList = res.data;
        });
      }
      if (newvalue === "") {
        this.isshowrulemessage = false;
      } else {
        this.isshowrulemessage = true;
      }
    }
  },
  created () {
    this.formData = {
      batchList: {}
    };
    maxTime = null
  },
  mounted () {
    this.search();
    this.getselectdatalist();
    this.queryFishPond();
  },
  methods: {
    //查询可选鱼塘
    queryFishPond () {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data;
      })
    },
    checkInt (rule, value, callback) {
      if (value) {
        if (Number(value) > 0) {
          callback();
        } else {
          return callback(new Error("请输入正确的数值！"));
        }
      }
    },
    checkInteger (rule, value, callback) {
      if (value) {
        if (Number(value) > 0 && Number(value) % 1 === 0) {
          callback();
        } else {
          return callback(new Error("请输入正确的数值！"));
        }
      }
    },
    staffChange (e) {
      this.staffList.find((item) => {
        if (item.staffId === e) {
          this.$set(this.formData, 'staffName', item.staffName)
          return true;
        }
      })
    },
    // 获取当前拥有类型表格
    getTableDataList () {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchList
        }
      };
      if (this.searchList?.date) {
        params.entity.samplingDateTimeStart = this.searchList.date[0] + ' 00:00:00';
        params.entity.samplingDateTimeEnd = this.searchList.date[1] + ' 23:59:59';
      }
      InPondEstimationApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.errCode !== undefined) {
          this.$message.error("表格获取失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取下拉框数据 start
    async getselectdatalist () {
      //   // 获取批次
      const { data: batch } = await batchApi.queryByCondition({
        breedTypeNo: "TRADITIONAL_BREED",
      });
      if (batch !== undefined) {
        this.batchList = batch;
      } else this.batchList = [];
      // 获取鱼塘
      const { data: resp } = await FishPondApi.queryByCondition({});
      if (resp !== undefined) {
        this.fishPondArr = resp;
      } else this.fishPondArr = [];
      const { data: staff } = await staffApi.queryByCondition({});
      if (staff !== undefined) {
        this.staffList = staff;
      } else this.staffList = [];
      this.getBatchByPond()//获取批次
    },
    // 根据批次品种查询 规格
    async specification (e) {
      const { data: specification } = await specificationApi.queryByCondition({
        fishVarietyId: e
      });
      if (specification !== undefined) {
        this.specificationList = specification;
      } else this.specificationList = [];
    },
    // 根据鱼塘查询批次
    getBatchByPond (e) {
      this.$set(this.formData, "batchList", undefined);
      batchApi.queryByCondition({ fishPondId: e, breedTypeNo: "TRADITIONAL_BREED", batchStatusList: ['CREATE', 'UN_COMPLETE'] }).then(res => {
        this.selectBatchList = res.data;
      })
    },
    batchChange (e) {
      maxTime = ''
      this.formData.samplingDateTime = new Date()
      this.selectBatchList.find(item => {
        console.log(item.productionBatchId, e)
        if (item.productionBatchId === e) {
          console.log('批次信息：', item)
          this.varietyName = item.varietyName
          this.samplingQuantityNum = item.num <= 100 ? item.num : 100
          if (this.samplingQuantityNum < this.formData.samplingQuantity) {
            this.formData.samplingQuantity = this.samplingQuantityNum
            this.samplingQuantityChange(this.samplingQuantityNum)
          }
          maxTime = new Date(item.buildDateTime)
          // this.formData.samplingDateTime = this.formatDateTimeMHS(maxTime)
        }
      })
    },
    // 通过品种id查估产规格
    getspecification (e) {
      this.batchChange(e.productionBatchId)
      this.$set(this.formData, "productionBatchId", e.productionBatchId);
      this.$set(this.formData, "fishVarietyId", e.fishVarietyId);
      if (this.formData.predictYieldDetailList) {
        this.formData.predictYieldDetailList.forEach((item) => { this.$set(item, 'specificationId', undefined) });
        this.$message.warning("请重新选择该批次的鱼品种对应规格");
      }
      this.fishPondArr.find((item, index) => {
        if (item.fishPondId === e.fishPondId) {
          this.formData.fishPondId = e.fishPondId;
          this.specification(e.fishVarietyId);
          return true
        } else if (index === this.fishPondArr.length - 1) {
          // this.formData.fishPondId = undefined;
          // this.$message.warning("该批次所关联鱼塘已被删除，请勿选择");
        }
      })
    },
    samplingQuantityChange (e) {
      console.log(e)
      // if (e > this.samplingQuantityNum) {
      //   e = this.samplingQuantityNum
      //   this.formData.samplingQuantity = this.samplingQuantityNum
      //   this.$message.info('一次估产最多抽检' + this.samplingQuantityNum + '尾')
      // }
      // if (e && e < 0) {
      //   this.formData.samplingQuantity = 0
      // }
      this.groupNum = Math.floor(e)
      this.formData.predictYieldDetailList = []
      if (Number(this.groupNum) > 0) {
        for (let i = 0; i < e; i++) {
          this.addCountList(i);
        }
        this.formData = { ...this.formData }
      } else {
        this.groupNum = ''
      }
    },
    // 添加一条清单列表
    addCountList (i) {
      // debugger 
      if (this.formData.productionBatchId) {
        if (this.formData.predictYieldDetailList === undefined || this.formData.predictYieldDetailList === null) this.$set(this.formData, "predictYieldDetailList", []);
        let Obj = { key: Date.now() };
        this.formData.predictYieldDetailList.push({ ...Obj });
        console.log(this.formData.predictYieldDetailList)
        this.groupNum = this.formData.predictYieldDetailList.length
        // 手动点击 '+'
        // if(i === undefined) this.$set(this.formData,'samplingQuantity',parseInt(this.formData.samplingQuantity) + 1)
        if (i === undefined) this.$set(this.formData, 'samplingQuantity', this.formData.predictYieldDetailList.length)
      } else {
        this.$message.warning("请先选择批次");
      }
    },
    // 删除一条清单列表
    delCountList (index) {
      if (this.formData.predictYieldDetailList.length === 1) {
        return;
      } else {
        this.formData.predictYieldDetailList.splice(index, 1);
        this.$set(this.formData, 'samplingQuantity', this.formData.samplingQuantity - 1)
        this.groupNum = this.formData.predictYieldDetailList.length
      }
    },
    // 获取下拉框数据 ends
    // 表格操作 增删改查 start
    async handleEdit (row) {
      console.log(row)
      this.varietyName = row.varietyName
      this.groupNum = row.predictYieldDetailList.length
      this.formData = {
        ...row,
        predictYieldDetailList: await this.queryDetail(row.predictYieldId)
      };
      this.selectBatchList.find(item => {
        if (item.productionBatchId === row.productionBatchId) {
          this.$set(this.formData, "batchList", {
            productionBatchId: row.productionBatchId,
            predictYieldId: row.predictYieldId,
          });
          this.specification(item.fishVarietyId);
        }
      });
      this.addActive = true;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
    },
    // 查询详情
    async queryDetail (e) {
      const {
        data: produce
      } = await InPondEstimationDetailApi.queryByCondition({
        predictYieldId: e
      });
      if (produce !== undefined) {
        return produce;
      } else return [];
    },
    // 获取批量删除list
    handleSelectionChange (list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.predictYieldId;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    delmessage () {
      if (this.nowChanceStau === "del") {
        InPondEstimationApi.delListById({ idList: this.nowselectedList }).then(
          res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          }
        );
        this.nowChanceStau = "";
      }
    },
    // 估产详情添加修改
    countList (e, st, index) {
      let errList = []
      let propList = [
        'predictYieldDetailList.' + index + '.weight',
        'predictYieldDetailList.' + index + '.num',
        'predictYieldDetailList.' + index + '.specificationId'
      ]
      this.$refs['formData'].validateField(propList,
        async err => { err ? errList.push(err) : '' })
      if (errList.length) {
        this.$message.info('请您完善估产信息后在点击添加/修改！')
      } else {
        if (!st || st === undefined) {
          let addparams = {
            ...e,
            predictYieldId: this.formData.predictYieldId
          };
          delete addparams.batchList;
          InPondEstimationDetailApi.add(addparams).then(async res => {
            if (res.success) {
              this.$set(this.formData, "predictYieldDetailList", await this.queryDetail(this.formData.predictYieldId));
              console.log(this.formData.predictYieldDetailList)
              this.$message.success("添加成功");
            } else {
              this.$message.error("添加失败");
            }
          });
        } else {
          let editparams = {
            ...e
          };
          InPondEstimationDetailApi.edit(editparams).then(res => {
            if (res.success) {
              this.$message.success("修改成功");
            } else {
              this.$message.error("修改失败");
            }
          });
        }
      }
    },
    // 弹框内部list 删除
    delProduceList (e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          InPondEstimationDetailApi.delById({ id: e.predictYieldDetailId }).then(res => {
            if (res.success) {
              this.formData.predictYieldDetailList.splice(index, 1);
              this.groupNum = this.formData.predictYieldDetailList.length
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    // 删除
    handleDelete (data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          InPondEstimationApi.delById({ id: data.predictYieldId }).then(res => {
            if (res.success) {
              this.resetActionBar()
              this.$message.success("删除成功");
              this.search();
            } else {
              this.resetActionBar()
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.resetActionBar()
          this.$message("取消删除");
        });
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        console.log(valid)
        // debugger
        if (valid) {
          if (this.nowChanceStau === "add") {
            let addparams = {
              ...this.formData,
              samplingDateTime: this.timestampToTime(new Date(this.formData.samplingDateTime).getTime())
            };
            delete addparams.batchList;
            console.log('this.groupNum-this.groupNum', this.groupNum);
            if (!this.groupNum) {
              this.$message('请完善估产组数')
              return
            }
            InPondEstimationApi.add(addparams).then(res => {
              // console.log('添加的***res',res);
              if (res.success) {
                if (parseFloat(res.data.estimateDensity) > parseFloat(res.data.density)) {
                  this.$alert('当前实际养殖密度大于标准养殖密度', '提示', {
                    confirmButtonText: '确定', type: 'warning',
                    callback: action => {
                      this.$message.success("添加成功");
                      this.search();
                    }
                  });
                } else {
                  this.$message.success("添加成功");
                  this.search();
                }
              } else if (res.errCode === 200) {
                this.$message.error(res.message);
              } else {
                this.$message.error("添加失败");
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let editparams = {
              ...this.formData
            };
            delete editparams.batchList;
            let notEidtIndex = []
            let getWeightList = this.formData.predictYieldDetailList.filter((item, index) => {
              if (!item.predictYieldId) notEidtIndex.push(index + 1);
              return !item.predictYieldId
            })
            console.log(getWeightList)
            if (!getWeightList.length) {
              console.log('editparams*****', editparams);
              InPondEstimationApi.edit(editparams).then(res => {
                if (res.success) {
                  if (parseFloat(res.data.estimateDensity) > parseFloat(res.data.density)) {
                    this.$alert('当前实际养殖密度大于标准养殖密度', '提示', {
                      confirmButtonText: '确定', type: 'warning',
                      callback: action => {
                        this.$message.success("修改成功");
                        this.search();
                      }
                    });
                  } else {
                    this.$message.success("修改成功");
                    this.search();
                  }
                } else if (res.errCode === 200) {
                  this.$message.error(res.message);
                } else {
                  this.$message.error("修改失败");
                }
              });
            } else {
              this.$message.error('您添加的第' + notEidtIndex.join('、') + '组称重数据未保存，请点击添加后保存！')
            }
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
    // 表格操作 增删改查 end
  }
};
</script>
<style lang="scss" scoped>
.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;

  .line-click {
    width: 30px;
    height: 30px;
    background-color: rgb(198, 196, 196);
    display: flex;
    justify-content: center;
    align-items: center;
    border: rgb(214, 214, 214) 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;

    .el-icon-minus {
      color: white;
    }
  }
}

.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  position: relative;
  right: 0;
  cursor: pointer;

  .el-icon-plus {
    color: white;
  }
}

.line-clicks {
  width: 30px;
  height: 30px;
  // background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  // border: rgb(214, 214, 214) 1px solid;
  color: red;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  text-decoration: underline;
  text-underline-position: under;
  position: relative;
  right: 0;
  cursor: pointer;
}

::v-deep .el-form-item {
  .el-form-item {
    margin-bottom: 20px;
  }
}

::v-deep .el-dialog {
  .el-dialog__body {
    max-height: 65vh;
  }
}

.addE {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
</style>
